import React, { useMemo } from 'react';
import type { FormInstance } from 'antd';
import type { BizRuleInstanceInfo } from '@/api/rulesInstance';
import { type BizAlarmRuleInfo, rulesWarningListApi } from '@/api/rulesWarning';
import { type DeviceItem, deviceManagerListApi } from '@/api/deviceManagerApi';
import { type DeviceGroup, deviceGroupListApi } from '@/api/deviceGroupApi';
import RemoteSelect, { type FetchParams } from '@/components/RemoteSelect';
import { EnableStatusType, objToArray } from '@/constants';

// 将枚举对象转换为Select组件需要的选项数组
const statusOptions = objToArray(EnableStatusType);

interface InstanceAddFormProps {
  form: FormInstance;
  data?: Partial<BizRuleInstanceInfo>;
  mode: 'add' | 'edit';
}

/**
 * 规则实例添加/编辑表单组件
 */
const InstanceAddForm: React.FC<InstanceAddFormProps> = ({ form, data, mode }) => {
  const [ruleList, setRuleList] = useState<any>([]);
  /** 获取告警规则列表 */
  const fetchRemoteSelectDataAlarmRule = async (params: FetchParams) => {
    const res = await rulesWarningListApi(params);
    if (res.success) {
      const { page, pageSize } = params;
      const hasMore = page * pageSize < res.data.total;
      setRuleList(res.data.records);
      return {
        data: res.data.records.map((v: BizAlarmRuleInfo) => ({
          ...v,
          label: v.alarmRuleName || '未命名告警规则',
          disabled: !v.ruleId,
          value: v.ruleId,
        })),
        total: res.data.total,
        hasMore,
      };
    }
    return {
      data: [],
      total: 0,
      hasMore: false,
    };
  };

  /** 获取设备分组列表 */
  const fetchRemoteSelectDataDeviceGroup = async (params: FetchParams) => {
    const res = await deviceGroupListApi(params);
    if (res.success) {
      const { page, pageSize } = params;
      const hasMore = page * pageSize < res.data.total;

      return {
        data: res.data.records.map((v: DeviceGroup) => ({
          ...v,
          label: `${v.groupName}(${v.deviceCount || 0})`,
          value: v.id,
        })),
        total: res.data.total,
        hasMore,
      };
    }
    return {
      data: [],
      total: 0,
      hasMore: false,
    };
  };

  /** 获取设备列表 */
  const fetchRemoteSelectDataDevice = async (params: FetchParams) => {
    const res = await deviceManagerListApi(params);
    if (res.success) {
      const { page, pageSize } = params;
      const hasMore = page * pageSize < res.data.total;

      return {
        data: res.data.records.map((v: DeviceItem) => ({
          ...v,
          label: `${v.deviceName}-${v.code}`,
          value: v.id,
          deviceCode: v.code,
          productCode: v.productCode,
        })),
        total: res.data.total,
        hasMore,
      };
    }
    return {
      data: [],
      total: 0,
      hasMore: false,
    };
  };

  const isEdit = mode === 'edit';

  // 监听绑定类型和分组ID的变化
  const bindType = AForm.useWatch('bindType', form);
  const groupId = AForm.useWatch('groupId', form);

  // 根据绑定类型和分组ID生成设备查询参数
  const deviceParams = useMemo(() => {
    return {
      groupId: bindType === 1 ? '' : groupId,
    };
  }, [groupId, bindType]);

  useEffect(() => {
    if (isEdit && data) {
      // 处理告警规则信息
      if (data.alarmRuleName) {
        const ruleId = ruleList.find(
          (item: any) => item.alarmRuleName === data.alarmRuleName
        )?.ruleId;
        form.setFieldValue('ruleId', ruleId);
        form.setFieldValue('alarmRuleName', data.alarmRuleName);
      }

      // 处理设备信息
      if (data.deviceList && Array.isArray(data.deviceList)) {
        const deviceIds = data.deviceList.map((device: any) => device.id);
        form.setFieldValue('deviceIds', deviceIds);
        form.setFieldValue(
          'devices',
          data.deviceList.map((device: any) => ({
            deviceCode: device.code,
            productCode: device.productCode,
          }))
        );
      }
    }
  }, [isEdit, data, form, ruleList]);

  return (
    <>
      <AForm.Item
        name="ruleInstanceName"
        label="规则实例名称"
        rules={[{ required: true, message: '请输入规则实例名称' }]}
      >
        <AInput placeholder="请输入规则实例名称" maxLength={50} />
      </AForm.Item>

      <AForm.Item
        name="ruleId"
        label="告警规则"
        rules={[{ required: true, message: '请选择告警规则' }]}
      >
        <RemoteSelect
          searchable
          placeholder="请选择告警规则"
          fetchData={fetchRemoteSelectDataAlarmRule}
          onSelect={(value, option) => {
            form.setFieldValue('alarmRuleName', option.label);
          }}
        />
      </AForm.Item>

      <AForm.Item
        label="绑定设备"
        name="bindType"
        initialValue={1}
        rules={[{ required: true, message: '请选择绑定设备' }]}
      >
        <ARadio.Group
          onChange={() => {
            form.setFieldValue('deviceIds', []);
            form.setFieldValue('groupId', undefined);
          }}
          options={[
            {
              value: 1,
              label: '不通过设备分组',
            },
            {
              value: 2,
              label: '通过设备分组',
            },
          ]}
        />
      </AForm.Item>

      {bindType === 2 && (
        <AForm.Item
          label="选择设备分组"
          name="groupId"
          rules={[{ required: true, message: '请选择设备分组' }]}
        >
          <RemoteSelect
            onSelect={() => {
              form.setFieldValue('deviceIds', []);
            }}
            searchable
            placeholder="请选择设备分组"
            fetchData={fetchRemoteSelectDataDeviceGroup}
          />
        </AForm.Item>
      )}

      <AForm.Item
        label="已选择设备列表"
        name="deviceIds"
        rules={[{ required: true, message: '请选择设备' }]}
      >
        <RemoteSelect
          searchable
          searchParams={deviceParams}
          mode="multiple"
          placeholder="请选择设备"
          onSelect={(values, options) => {
            console.log('onSelect values:', values);
            console.log('onSelect options:', options);
            // 构建devices数组，包含deviceCode和productCode
            const devices = Array.isArray(options) ? options.map((option: any) => option.data) : [];
            console.log('构建的devices数组:', devices);
            form.setFieldValue('devices', devices);
          }}
          fetchData={fetchRemoteSelectDataDevice}
        />
      </AForm.Item>

      <AForm.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
        <ASelect placeholder="请选择状态" options={statusOptions} allowClear={false} />
      </AForm.Item>

      <AForm.Item name="remark" label="规则描述" rules={[{ required: false }]}>
        <AInput.TextArea placeholder="请输入规则描述" maxLength={200} showCount rows={4} />
      </AForm.Item>

      {/* 隐藏字段，用于编辑模式 */}
      {isEdit && (
        <AForm.Item name="id" hidden>
          <AInput />
        </AForm.Item>
      )}

      {/* 隐藏字段，用于存储选中的名称和设备信息 */}
      <AForm.Item name="alarmRuleName" hidden>
        <AInput />
      </AForm.Item>
      <AForm.Item name="devices" hidden>
        <AInput />
      </AForm.Item>
    </>
  );
};

export default InstanceAddForm;
